from django.db import models
from users.models import MyUser
from stock.models import Stock
from django.db.models.signals import pre_save
from django.dispatch import receiver
from django.db.models import Q
from django.utils import timezone


# Create your models here.
class Order(models.Model):
    user = models.ForeignKey(MyUser, on_delete=models.CASCADE, related_name='user_orders')
    stock = models.ForeignKey(Stock, on_delete=models.CASCADE, related_name='stock_orders')
    type = models.BooleanField()
    ctime = models.DateTimeField(verbose_name='创建时间', default=timezone.now, null=True)
    undealed = models.IntegerField(verbose_name='未成交数量')
    dealed = models.IntegerField(verbose_name='已成交数量', default=0)
    canceled = models.IntegerField(verbose_name='取消数量', default=0)
    price = models.DecimalField(verbose_name='股票价格', decimal_places=3, max_digits=10)

    def __str__(self):
        if self.type == 0:
            order_type = "买订单"
        else:
            order_type = "卖订单"
        return self.user.username + order_type + self.stock.name + "价格" + str(self.price) + "未成交数量" + str(self.undealed)

    class Meta:
        ordering = ['-price','ctime']


""":arg

@receiver(pre_save, sender=Order)
def autoexchange(sender, instance, **kwargs):
    if instance.type == 0:
        print("要被处理的订单是购买{0}订单，他的未成交数量是{1}".format(instance.stock.name, instance.undealed))
        orderlist = Order.objects.filter(
            ~Q(user_id=instance.user_id)&
            Q(stock_id=instance.stock_id) &
            Q(type=instance.type)).order_by('ctime')
        total = instance.undealed
        print(orderlist)
        for order in orderlist:
            if total - order.undealed > 0:
                total -= order.undealed
            print(order.ctime)

    elif instance.type == 1:
        print("要被处理的订单是卖出{0}订单，他的未成交数量是{1}".format(instance.stock.name, instance.undealed))



"""
